<?php

namespace App\Http\Repositories\UserManage;

use App\Http\Repositories\Relation\ResourceObjectRepo;
use App\Http\Repositories\Relation\TypeObjectRepo;
use App\Http\Repositories\Relation\UserRoleRepo;
use App\Http\Repositories\Repository;
use App\Models\Business;
use App\Models\ResourceObject;
use App\Traits\HelpFunctions;
use Illuminate\Support\Facades\DB;

/**
 * 服务商信息
 */
class BusinessRepo extends Repository
{
    use HelpFunctions;

    const MODEL = Business::class;

    public function search(array $params)
    {
        $query = $this->query()
            ->select('businesses.*', 'users.name as user_name', 'users.phone', 'type_object_relation.type')
            ->leftJoin('users', 'users.id', '=', 'businesses.user_id')
            ->leftJoin('type_object_relation', 'type_object_relation.object_id', '=', 'businesses.id')
            ->where('type', config('project.type.business'));

        if (!empty($params['type_ids'])) {
            $query->whereIn('type_id', $params['type_ids']);
        }
        if (!empty($params['corporation_name'])) {
            $query->where('corporation_name', 'like', '%' + $params['corporation_name'] + '%');
        }
        if (!empty($params['corporation_card_id'])) {
            $query->where('corporation_card_id', 'like', '%' + $params['corporation_card_id'] + '%');
        }
        if (!empty($params['name'])) {
            $query->where('name', 'like', '%' + $params['name'] + '%');
        }
        if (!empty($params['user_name'])) {
            $query->where('user_name', 'like', '%' + $params['user_name'] + '%');
        }
        if (!empty($params['phone'])) {
            $query->where('phone', 'like', '%' + $params['phone'] + '%');
        }
        if (!empty($params['landline'])) {
            $query->where('landline', 'like', '%' + $params['landline'] + '%');
        }
        if (!empty($params['province_id'])) {
            $query->where('province_id', $params['province_id']);
        }
        if (!empty($params['city_id'])) {
            $query->where('city_id', $params['city_id']);
        }
        if (!empty($params['area_id'])) {
            $query->where('area_id', $params['area_id']);
        }
        if (!empty($params['status'])) {
            $query->where('status', $params['status']);
        }
        if (!empty($params['readed'])) {
            $query->where('readed', $params['readed']);
        }
        // 'serve_begin_time',
        // 'serve_end_time',
        if (!empty($params['begin_time'])) {
            $query->where('created_at', '>=', $params['begin_time']);
        }
        if (!empty($params['end_time'])) {
            $query->where('created_at', '<=', $params['end_time']);
        }

        $query->with(['resourceObjectCardIds', 'resourceObjectLicences', 'types']);

        return $this->paginate($query, $params["paginate"] ?? true, $params["page_num"] ?? 10);
    }

    public function getOneById(int $id)
    {
        $query = $this->query()
            ->leftJoin('users', 'users.id', '=', 'businesses.user_id')
            ->select('businesses.*', 'users.name as user_name', 'users.phone')
            ->where('businesses.id', $id)
            ->with(['resourceObjectCardIds', 'resourceObjectLicences', 'types'])
            ->first();

        return !empty($query) ? $query->toArray() : [];
    }

    public function createOne(array $params)
    {
        //business参数
        $business_args = $this->getBusinessArgs($params);

        //事务处理
        DB::beginTransaction();

        try {
            //添加business数据
            $business = parent::createOne($business_args);
            $object_id = $business->id;

            //添加resource_object数据
            $resource_licence_args = $this->getResourceObjectArgs(
                $params['resources']['licence'],
                ['type' => config('project.resource.licence'), 'object_id' => $object_id]
            );
            $resource_card_id_args = $this->getResourceObjectArgs(
                $params['resources']['card_id'],
                ['type' => config('project.resource.corporation_card_id'), 'object_id' => $object_id]
            );
            $resource_object = new ResourceObjectRepo;
            $resource_object->createMany(array_merge($resource_licence_args, $resource_card_id_args));

            //添加type_object_relation数据
            $type_args = $this->getTypeObjectArgs(
                $params['types'],
                ['object_id' => $object_id, 'type' => config('project.type.business')]
            );
            $type_object = new TypeObjectRepo;
            $type_object->createMany($type_args);

            app(UserRoleRepo::class)->create($business_args['user_id'], app(RoleRepo::class)->getRoleIdByAlias('service'));

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            abort(500, $e->getMessage());
        }

        return $this->getOneById($object_id);
    }

    public function deleteById(int $id)
    {
        DB::beginTransaction();
        try {
            $business = $this->getOneById($id);
            parent::deleteById($id);

            $resource_object = new ResourceObjectRepo;
            $resource_object->deleteByConditions(['type' => config('project.resource.licence'), 'object_id' => $id]);
            $resource_object->deleteByConditions(['type' => config('project.resource.corporation_card_id'), 'object_id' => $id]);

            $type_object = new TypeObjectRepo;
            $type_object->deleteByConditions(['type' => config('project.type.business'), 'object_id' => $id]);

            app(UserRoleRepo::class)->delete($business['id'], app(RoleRepo::class)->getRoleIdByAlias('service'));

            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            abort(500, $e->getMessage());
        }
    }

    public function editById(int $id, array $params)
    {
        //handle params

        //business参数
        $business_args = $this->getBusinessArgs($params);
        //delete resource_object condition
        $delete_resource_licence_args = ['type' => config('project.resource.licence'), 'object_id' => $id];
        $delete_resource_card_id_args = ['type' => config('project.resource.corporation_card_id'), 'object_id' => $id];
        $delete_type_object = ['object_id' => $id, 'type' => config('project.type.business')];

        //update args
        if (!empty($params['resources'])) {
            $resource_licence_args = $this->getResourceObjectArgs(
                $params['resources']['licence'],
                ['type' => config('project.resource.licence'), 'object_id' => $id]
            );
            $resource_card_id_args = $this->getResourceObjectArgs(
                $params['resources']['card_id'],
                ['type' => config('project.resource.corporation_card_id'), 'object_id' => $id]
            );
        }
        if (!empty($params['types'])) {
            $type_args = $this->getTypeObjectArgs(
                $params['types'],
                ['object_id' => $id, 'type' => config('project.type.business')]
            );
        }


        //begin transactin
        DB::beginTransaction();
        try {
            //更新business
            parent::editById($id, $business_args);

            //delete
            app(ResourceObjectRepo::class)->deleteByConditions($delete_resource_licence_args);
            app(ResourceObjectRepo::class)->deleteByConditions($delete_resource_card_id_args);
            app(TypeObjectRepo::class)->deleteByConditions($delete_type_object);

            //添加resource_object数据
            (!empty($resource_licence_args) || !empty($resource_card_id_args))
                &&
                app(ResourceObjectRepo::class)->createMany(array_merge($resource_licence_args ?? [], $resource_card_id_args ?? []));

            //添加type_object_relation数据
            !empty($type_args)
                &&
                app(TypeObjectRepo::class)->createMany($type_args);

            DB::commit();
        } catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            abort(500, $e->getMessage());
        }
        return $this->getOneById($id);
    }
}
